package server;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import entity.User;
import service.UserServiceImpl;
import utils.ServerConfig;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

//服务器聊天端口
public class Server implements Runnable{
    private UserServiceImpl userService;

    public Server(UserServiceImpl userService) {
        this.userService=userService;
    }

    public void run() {
        try{
            userService.deleteAll();
            userService.deleteuALlserport();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ServerSocket serverSocket=null;
        Socket socket=null;
        InputStream inputStream=null;
        ByteOutputStream byteOutputStream=null;
        byte[] bytes=null;
        try {
            //开启聊天端口
            serverSocket = new ServerSocket(ServerConfig.serverConfig("ServerPort"));
            while (true){
                System.out.println("以创建连接，等待连接-----");
                //等待加入
                socket = serverSocket.accept();
                System.out.println("Server已连接："+socket.getInetAddress().toString());
                inputStream = socket.getInputStream();
                byteOutputStream = new ByteOutputStream();
                bytes = new byte[1024];
                int len;
                while ((len= inputStream.read(bytes))!=-1){
                    byteOutputStream.write(bytes,0,len);
                }

                //查找mysql中同一聊天室下在线用户
                User serverport = userService.findByPort(socket.getInetAddress().toString());
                System.out.println(serverport.getServerport()+"  "+byteOutputStream.toString());
                //将信息发送至同一聊天室的其他用户
                for (User user:userService.findAll()) {
                    if(user.getServerport()!=(int)serverport.getServerport()){
                        String message=serverport.getName()+": "+byteOutputStream.toString();
                        System.setProperty(String.valueOf(user.getServerport()),message);
                    }
                }
                inputStream.close();
                socket.close();
            }

        } catch (IOException e) {
        }finally {
            try {
                byteOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
